package bspay

import (
	"encoding/json"
	"errors"

	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bspay/bspay/tool"
)

type WithdrawResp struct {
	Err      int    `json:"Err"`
	OrdId    string `json:"ord_id"`
	SerialId string `json:"serial_id"`
	ErrMsg   string `json:"err_msg"`
}
type PayResp struct {
	Err      int    `json:"err"`
	Url      string `json:"url"`
	OrdId    string `json:"ord_id"`
	SerialId string `json:"serial_id"`
	ErrMsg   string `json:"err_msg"`
}

// 代收（付款）BsPay
func BsPay(url, appKey, orderId, notifyUrl, redirect, SecretKey, amount string) (resp PayResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["app_key"] = appKey
	params["amount"] = amount
	params["ord_id"] = orderId
	params["notify_url"] = notifyUrl
	params["redirect"] = redirect
	if v, err := tool.GenerateSignature(params, SecretKey); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
	}
	output, err := tool.SendPostJson(url, params)

	if err != nil {
		return resp, err
	}
	var result PayResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Err != 0 {
		return resp, errors.New(result.ErrMsg)
	}
	return result, nil
}

// 代付（提现）Withdraw
func Withdraw(url, appKey, amount, orderId, card, name, bankCode, notifyUrl, SecretKey string) (resp WithdrawResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["app_key"] = appKey
	params["amount"] = amount
	params["ord_id"] = orderId
	params["card"] = card
	params["name"] = name
	params["p_bank_code"] = bankCode
	params["notify_url"] = notifyUrl
	params["notify_url"] = notifyUrl

	if v, err := tool.GenerateSignature(params, SecretKey); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
	}
	output, err := tool.SendPostJson(url, params)
	if err != nil {
		return resp, err
	}
	var result WithdrawResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Err != 0 {
		return resp, errors.New(result.ErrMsg)
	}
	return result, nil
}
